package xyz.yuanjilu.service.impl;



import java.io.IOException;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.connection.Connection;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;

import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.ShutdownSignalException;

import xyz.yuanjilu.service.MQSubscribe;

public class DemoSubscribe  implements MQSubscribe {
	

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	private final static String EXCHANGE_NAME = "ex_publish"; 
	
	@Resource
	ConnectionFactory factory ;
	
	@PostConstruct
	public void init(){
		Connection connection = factory.createConnection();  
        Channel channel = connection.createChannel(false);  
        // 声明转发器和类型  
        try {
			channel.exchangeDeclare(EXCHANGE_NAME, "fanout" );
		
	        String queueName = channel.queueDeclare().getQueue();
	        channel.queueBind(queueName, EXCHANGE_NAME, "");
	
	        channel.basicConsume(queueName, true, this);
        } catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
	}

	@Override
	public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body)
			throws IOException {
		 String message = new String(body, "UTF-8");
         
         logger.info(this.toString()+"订阅到消息--"+new String(message));
	}

	@Override
	public void handleConsumeOk(String consumerTag) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void handleCancelOk(String consumerTag) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void handleCancel(String consumerTag) throws IOException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void handleShutdownSignal(String consumerTag, ShutdownSignalException sig) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void handleRecoverOk(String consumerTag) {
		// TODO Auto-generated method stub
		
	}

}
